# -*- coding: utf-8 -*-
"""
插件管理器
"""
import os
import sys
import importlib.util
from typing import List, Dict
from .plugin_base import PluginBase


class PluginManager:
    """插件管理器"""
    
    def __init__(self):
        self._plugins: List[PluginBase] = []
        self._plugin_dir = os.path.join(os.path.dirname(__file__), 'plugins')
    
    def load_plugins(self, load_defaults=True):
        """加载所有插件
        
        Args:
            load_defaults (bool, optional): 是否加载默认插件. Defaults to True.
        """
        if not load_defaults:
            return
            
        if not os.path.exists(self._plugin_dir):
            print(f"Plugin directory not found: {self._plugin_dir}")
            return
        
        # 遍历插件目录
        for item in os.listdir(self._plugin_dir):
            item_path = os.path.join(self._plugin_dir, item)
            
            # 检查是否是Python文件
            if os.path.isfile(item_path) and item.endswith('.py') and not item.startswith('__'):
                self._load_plugin_from_file(item_path)
            # 检查是否是包目录
            elif os.path.isdir(item_path) and not item.startswith('__'):
                init_file = os.path.join(item_path, '__init__.py')
                if os.path.exists(init_file):
                    self._load_plugin_from_package(item_path)
    
    def _load_plugin_from_file(self, file_path: str):
        """从文件加载插件"""
        try:
            # 获取模块名
            module_name = os.path.splitext(os.path.basename(file_path))[0]
            
            # 确保ui目录在sys.path中
            ui_dir = os.path.dirname(os.path.dirname(file_path))  # 获取ui目录
            if ui_dir not in sys.path:
                sys.path.insert(0, ui_dir)
            
            # 动态导入模块
            spec = importlib.util.spec_from_file_location(module_name, file_path)
            if spec and spec.loader:
                module = importlib.util.module_from_spec(spec)
                
                # 设置模块的__package__属性以支持相对导入
                module.__package__ = 'ui.plugins'
                
                spec.loader.exec_module(module)
                
                # 查找插件类
                plugin_class = self._find_plugin_class(module)
                if plugin_class:
                    plugin_instance = plugin_class()
                    plugin_instance.initialize()
                    self._plugins.append(plugin_instance)
                    print(f"Loaded plugin: {plugin_instance.get_name()}")
                
        except Exception as e:
            print(f"Error loading plugin from {file_path}: {e}")
    
    def _load_plugin_from_package(self, package_path: str):
        """从包目录加载插件"""
        try:
            # 获取包名
            package_name = os.path.basename(package_path)
            
            # 添加到系统路径
            parent_dir = os.path.dirname(package_path)
            if parent_dir not in sys.path:
                sys.path.insert(0, parent_dir)
            
            # 动态导入包
            module = importlib.import_module(package_name)
            
            # 查找插件类
            plugin_class = self._find_plugin_class(module)
            if plugin_class:
                plugin_instance = plugin_class()
                plugin_instance.initialize()
                self._plugins.append(plugin_instance)
                print(f"Loaded plugin: {plugin_instance.get_name()}")
                
        except Exception as e:
            print(f"Error loading plugin from {package_path}: {e}")
    
    def _find_plugin_class(self, module):
        """在模块中查找插件类"""
        print(f"Searching for plugin class in module: {module.__name__}")
        
        for name in dir(module):
            obj = getattr(module, name)
            print(f"  Checking object: {name} - {type(obj)}")
            
            if isinstance(obj, type):
                print(f"    {name} is a class")
                print(f"    MRO: {obj.__mro__}")
                
                # 检查是否继承自PluginBase
                if hasattr(obj, '__bases__'):
                    for base in obj.__bases__:
                        print(f"    Base class: {base.__name__} from {base.__module__}")
                        if base.__name__ == 'PluginBase':
                            print(f"    Found PluginBase inheritance!")
                            return obj
                
                # 备用检查：通过类名查找
                if (issubclass(obj, PluginBase) and 
                    obj is not PluginBase):
                    print(f"    Found plugin class via issubclass: {name}")
                    return obj
        
        print(f"  No plugin class found in module {module.__name__}")
        return None

    def add_plugin(self, plugin_instance: PluginBase):
        """添加一个插件实例"""
        if isinstance(plugin_instance, PluginBase):
            plugin_instance.initialize()
            self._plugins.append(plugin_instance)
            print(f"Added plugin: {plugin_instance.get_name()}")
        else:
            print(f"Invalid plugin instance provided.")

    def get_plugins(self) -> List[PluginBase]:
        """获取所有已加载的插件"""
        return self._plugins
    
    def get_plugin_by_name(self, name: str) -> PluginBase | None:
        """根据名称获取插件"""
        for plugin in self._plugins:
            if plugin.get_name() == name:
                return plugin
        return None
    
    def unload_all_plugins(self):
        """卸载所有插件"""
        for plugin in self._plugins:
            try:
                plugin.cleanup()
            except Exception as e:
                print(f"Error cleaning up plugin {plugin.get_name()}: {e}")
                import traceback
                traceback.print_exc()
        self._plugins.clear() 